package org.sample.commons.io;

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import javax.imageio.*;

public class CaptchaUtils {
    // 定义图形验证码中绘制字符的字体
    private final static Font font = new Font("Arial Black", Font.PLAIN, 16);

    // 定义图形验证码的大小
    private static final int Width = 70;
    private static final int Height = 18;

    private static final Random random = new Random();

    public static void writeImage(String str, OutputStream os) throws IOException {
        BufferedImage image = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 填充背景色并预留1px边框
        g.setColor(getRandColor(200, 250));
        g.fillRect(1, 1, Width - 2, Height - 2);

        g.setColor(getRandColor(160, 200));
        // 生成随机干扰线
        for (int i = 0; i < 80; i++) {
            int x = random.nextInt(Width - 1);
            int y = random.nextInt(Height - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g.drawLine(x, y, x + xl, y + yl);
        }
        for (int i = 0; i < 80; i++) {
            int x = random.nextInt(Width - 1);
            int y = random.nextInt(Height - 1);
            int xl = random.nextInt(12) + 1;
            int yl = random.nextInt(6) + 1;
            g.drawLine(x, y, x - xl, y - yl);
        }

        float yawpRate = 0.1f;
        int area = (int) (yawpRate * Width * Height);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(Width);
            int y = random.nextInt(Height);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        // 设置绘制字符的字体
        g.setFont(font);

        for (int i = 0; i < str.length(); i++) {
            Character tmp = str.charAt(i);
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(tmp.toString(), 15 * i + 10, 15);
        }
        g.dispose();
        // 向输出流中输出图片
        ImageIO.write(image, "JPEG", os);
    }

    // 定义一个获取随机颜色的方法
    private static Color getRandColor(int fc, int bc) {
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRGB();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRGB() {
        int[] rgb = new int[3];
        for (int i = 0; i < rgb.length; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

}